﻿const dw = require('./db-worker');
const https = require('https');
const
    SYS = 'HumanSMS',
    PASSWORD = 'wDAoIU0DbcSzIGoK6YXnr9LA0Er8R1$Kfrw9ukM51mwaCkHf7k!TUDY49*6Eq~4s',
    HOSTNAME = '172.20.101.3',
    PORT = 8086,
    PATH = '/send',
    METHOD = 'POST',
    TYPE = 'sms';

module.exports = async function (req, res) {
    var eno = req.session && req.session.uid;
    var { msg, receivers } = req.body;

    if (!eno || !msg || !receivers) {
        res.end();
        return;
    }

    console.log(`===receivers===`);
    console.log(receivers+'\r\n');

    let { msgId, rowset } = await dw.transormReceivers(JSON.stringify(receivers));

    console.log(`====rowset====:+\r\n${rowset.join()}\r\n`);

    let data = {
        sys: SYS,
        password: PASSWORD,
        sender: eno,
        senderIp: req.ip,
        type: TYPE,
        receivers: rowset.join(),
        msg
    }
    try {       
        let raw = await send(JSON.stringify(data));

        console.log(`echo from gateway: ${raw}\r\n`);

        if (raw) {
            let echo = JSON.parse(raw);
            if (echo && echo.success === true) {
                await dw.setStage1MsgGroup(msgId, echo.msgGroup);
                res.end('success!')
                return
            }
        }
        res.end('unknown error!');
    }
    catch (e) {
        console.log(e);
        res.end('failed to send message.')
    }
}

async function send(data) {
    return await new Promise(function (resolve, reject) {
        const options = {
            host: HOSTNAME,
            port: PORT,
            path: PATH,
            method: METHOD,
            rejectUnauthorized: false,
            headers: {
                'Content-Type': 'application/json',
                'Content-Length': Buffer.byteLength(data)
            }
        };
        const req = https.request(options, (res) => {
            var data = '';
            res.on('data', (chunk) => data = data + chunk);
            res.on('end', () => resolve(data))
        });
        req.on('error', (e) => {
            console.error(e);
            reject(e.message)
        });
        req.write(data);
        req.end();
    })
}